<?php
// 购物车
namespace app\shop\controller;

use think\Db;
use think\Cache;
use think\Session;
use think\Request;
use think\Controller;
use app\shop\common\Des;
use app\shop\model\ShopSpecAttr;
use app\shop\model\Config as ConfigModel;
use app\shop\model\RedPacket as RedPacketModel;
use app\shop\model\ShopGoods as ShopGoodsModel;
use app\shop\model\MemberBrowse as MemberBrowseModel;
use app\shop\model\MemberPacket as MemberPacketModel;
use app\shop\model\MemberCoupon as MemberCouponModel;
use app\shop\model\MemberAddress as MemberAddressModel;
use app\shop\model\ShopGoodsCombo as ShopGoodsComboModel;
use app\shop\model\FreightTemplate as FreightTemplateModel;
use app\shop\model\MemberShoppingCart as MemberShoppingCartModel;
use app\shop\model\TemporaryShoppingCart as TemporaryShoppingCartModel;

class ShopCart extends Controller
{

    /**
     * 购物车
     */
    public function index()
    {
        // 会员ID
        $memberId = Session::get('member_id');

        //查询会员购物车内商品
        $shopCart = (new MemberShoppingCartModel())->where('sun_member_shopping_cart.member_id', $memberId)
            ->with(['shopGoods' => function ($e) {
                $e->withField('id,member_id,rebate_percentage,thumb_img,title,freight,inventory');
            }])->select();

        //合并同一店铺商品
        $data = [];
        if ($shopCart) {
            foreach ($shopCart as $v) {
                $v->shopGoods->shop;
                $v['good_total'] = number_format($v['number'] * $v['price'], 2);
                $data[$v->shopGoods->shop->title][] = $v;
            }
        }


        return $this->fetch('', [
            'mate_head' => '购物车',
            'data'      => $data,

        ]);
    }


    /**
     * 立即购买
     */
    public function buy_now()
    {
        if (Request::instance()->isPost()) {
            // 获取会员ID  商品参数
            $memberId = Session::get('member_id');
            $data = Request::instance()->param();

            // 判断登录状态
            if (empty($memberId)) return ['code' => 401, 'message' => '您未登录，请先登录'];

            // 判断是否是自己店铺商品
            if ($memberId == $data['shop_id']) return ['code' => 402, 'message' => '自己不能购买自己的商品'];

            // 查看主库存
            $stock = (int)(new ShopGoodsModel())->where('id', $data['goods_id'])->value('inventory');
            if ($stock < $data['num']) return ['code' => 402, 'message' => '库存不足！请改日再购买！'];

            // 查看分库存
            $sub_inventory = (new ShopSpecAttr())->where(['goods_id' => $data['goods_id'], 'attribute' => $data['attr']])->find();

            if ($sub_inventory) {
                if ((int)$sub_inventory['inventory'] < $data['num']) return ['code' => 402, 'message' => '该属性库存不足！请改日再购买！'];
            }

            $model = new TemporaryShoppingCartModel();

            $map['member_id'] = Session::get('member_id');
            $map['goods_id'] = $data['goods_id'];
            $map['number'] = $data['num'];
            $map['limited_status'] = $data['special_status'];
            $map['attr'] = $data['attr'];
            //单价
            $map['price'] = (new ShopGoodsModel())->where(['id' => $map['goods_id']])->value('price');
            $find = db('group_goods')->where(['goods_id' => $map['goods_id']])->find();
            if($find){
                $map['price'] = $find['price'];
            }

            //查找商品价格(已选属性按属性算)
            if (Request::instance()->post('goods_attr_id')){   //选择了属性
                $price = (new ShopSpecAttr())->where(['id' => Request::instance()->post('goods_attr_id')])->field(['id','goods_id','price'])->find();
                if ($price['goods_id'] == $map['goods_id']){
                    $map['price'] = $price['price'];
                }
            }

            //有相同属性价格商品的物品合在一起
            $same = $model->where(['member_id' => Session::get('member_id'), 'goods_id' => $data['goods_id'], 'attr'  =>  $data['attr'], 'price' => $data['price']])->find();

            if ($same) {
                $return_id = $same['id'];
            } else {
                //存购物车
                $res = $model->isUpdate(false)->allowField(true)->save($map);
                $return_id = $model->id;
            }

            //成功返回购物车id
            return $return_id ? ['code' => 200, 'message' => $return_id] : ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }


    /**
     * 下订单时候佣金分配
     */
    public function brokerage($user_id, $price, $order_number, $shop_id = 0)
    {

        // 分销返利
        $hierarchy = Db::name('member_distribution')
            ->where(['referrals_id' => $user_id])
            ->order(['level' => 'desc'])
            ->value('hierarchy');

        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);      // 变成数组
            array_shift($hierarchy);                    // 去掉第一个key
            array_pop($hierarchy);                      // 去掉最后一个key
            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }

        // 查看是否开启店铺分销 Y是启用 N是未启用（N默认平台）
        if (Cache::get('web_distribution') == 'Y') {

            $shop = Db::name('shop')->where(['member_id' => $shop_id])->field('one_ratio,two_ratio,three_ratio')->find();

            // 一级分销佣金 给自己返钱
            if (isset($user_id)) {

                // 产生的佣金
                $brokerage = bcmul($price, ($shop['one_ratio'] / 100), 2);

                // 增加佣金 和 总数
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')->insert(['member_id' => $user_id, 'distribution_id' => $user_id, 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 二级分销佣金
            if (isset($hierarchy[0])) {

                // 产生的佣金
                $brokerage = bcmul($price, ($shop['two_ratio'] / 100), 2);

                // 增加佣金 和 总数
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[0], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 三级分销佣金
            if (isset($hierarchy[1])) {

                // 产生的佣金
                $brokerage = bcmul($price, ($shop['three_ratio'] / 100), 2);

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[1], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

        } else {

            // 一级分销佣金
            if (isset($user_id)) {

                // 产生的佣金
                $brokerage = bcmul($price, (Cache::get('web_one_ratio') / 100), 2);


                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')->insert(['member_id' => $user_id, 'distribution_id' => $user_id, 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 二级分销佣金
            if (isset($hierarchy[0])) {

                // 产生的佣金
                $brokerage = bcmul($price, (Cache::get('web_two_ratio') / 100), 2);

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[0], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 三级分销佣金
            if (isset($hierarchy[1])) {

                // 产生的佣金
                $brokerage = bcmul($price, (Cache::get('web_three_ratio') / 100), 2);

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[1], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

        }
    }


    /**
     * 确认订单（新） 优惠卷id可优化
     */
    public function confirm_order()
    {

        // 获取 购物车ID 红包ID 优惠券ID 地址ID
        $act = Request::instance()->param('act');
        $cart_id = Request::instance()->param('cart_id');
        $address_id = Request::instance()->param('address_id', '');
        $coupon_id = Request::instance()->param('coupon_id');
        $red_packet_id = Request::instance()->param('red_packet_id', '');
        $combo_has = Request::instance()->has('combo', 'param');
        // 实例化
        $cartModel = new MemberShoppingCartModel();
        $couponModel = new MemberCouponModel();
        $redPacketModel = new RedPacketModel();
        $temporaryShoppingCart = new TemporaryShoppingCartModel();


        // 规避跳转
        if (empty($cartModel::get($cart_id)) && empty($combo_has) &&empty($temporaryShoppingCart::get($cart_id))) $this->redirect('MemberOrder/index');

        //用户选择优惠券
        $couponids = explode(',', $coupon_id);

        //用户选择红包
        $packetData = $redPacketModel->where('id', $red_packet_id)->field('id,actual_price,title')->find();


        //从购物车表查出商品信息
        if ($act == "temporary") {
            $data = $temporaryShoppingCart->where('sun_temporary_shopping_cart.id', 'in', $cart_id)
                ->with(['shopGoods' => function ($e) {
                    $e->withField('id,member_id,rebate_percentage,charges,title,price,freight,thumb_img,goods_str');
                }])->select();
        }else{
            $data = $cartModel->where('sun_member_shopping_cart.id', 'in', $cart_id)
                ->with(['shopGoods' => function ($e) {
                    $e->withField('id,member_id,rebate_percentage,title,charges,price,freight,thumb_img,goods_id');
                }])->select();
        }


        //同一店铺商品合并
        $opt = [];
        foreach ($data as $value) {
            $value->shopGoods->shop;
            $opt[$value->shopGoods->shop->title]['data'][] = $value;
        }

        if (Request::instance()->has('combo', 'param')) {

            //查找套餐信息
            $opt = [];
            $comboArr = explode('|', Request::instance()->param('combo'));   //套餐id,属性串,套餐数量

            $combo_data = self::combo_list(Request::instance()->param('combo'), 'order_yes');

            $attr = explode(',', $comboArr[1]);
            foreach ($combo_data->shopGoodsComboSelected as $key => $item) {
                $item->shopGoods->shop;
                $attr_find = [];
                //有属性
                if ($attr[$key]) {
                    $attr_find = Db::name('shopSpecAttr')->where(['id' => $attr[$key]])->field('id,price,attribute')->find();
                }
                unset($item->shopSpecAttr, $item->sort, $item->combo_id, $item->goods_attr_id);
                $item['price'] = $attr_find ? $attr_find['price'] : $item->shopGoods->price;
                $item['charges'] = $item->shopGoods->charges;
                $item['number'] = $comboArr[2];    //购买数量
                $item['member_id'] = Session::get('member_id');
                $item['limited_status'] = 0;
                $item['goods_id'] = $item->shopGoods->id;  //商品id
                $item['attr'] = $attr_find ? $attr_find['attribute'] : '';   //属性
                $opt[$item->shopGoods->shop->title]['shop_id'] = $combo_data->shop_id;
                $opt[$item->shopGoods->shop->title]['combo_price'] = bcmul($combo_data->combo_price, $comboArr[2], 2);
                $opt[$item->shopGoods->shop->title]['data'][] = $item;
            }

        }
        //用户默认收货地址
        $address = (new MemberAddressModel)->where(['member_id' => Session::get('member_id'), 'status' => 1])->field('id,name,phone,address,area_info,template_id')->find();

        //用户选择收货地址来替换默认
        if ($address_id && $address_id != 'undefined') {
            $address = (new MemberAddressModel)->where('id', $address_id)->field('id,name,phone,address,area_info,template_id')->find();
        }

        if (Request::instance()->has('combo', 'param')) {
            $m_key = array_keys($opt);
            $opt = reset($opt);

            $total['total_price'] = $opt['combo_price'];
            $total['total_number'] = 1;
            $keyArr = "";
            // $num = 0;
            $opt['shop_number'] = 1;
            $opt['shop_price'] = $opt['combo_price'];
            $opt['shop_freight'] = 0;
            $opt['red_packet_id'] = 0;
            $opt['red_actual_price'] = "";
            $opt['coupon_id'] = 0;
            $opt['coupon_actual_price'] = "";
            $opt['charges'] = "";
            foreach ($opt['data'] as $vv) {
                $opt['charges'] += bcmul($vv->shopGoods['charges'], $vv['number'], 2);

            }
            $arr[reset($m_key)] = $opt;
            $opt = $arr;

        } else {
            // 订单 总价格 总数量
            $total['total_price'] = 0;
            $total['total_number'] = 0;
            $keyArr = "";
            $num = 0;

            foreach ($opt as $k => &$v) {

                //单店铺商品数量合计
                $v['shop_number'] = 0;
                //单店铺价格合计
                $v['shop_price'] = 0;
                //单店铺运费合计
                $v['shop_freight'] = 0;
                // 使用红包
                $v['red_packet_id'] = 0;
                $v['red_actual_price'] = "";
                $v['charges'] = 0;
                // 统计每个店铺的订单的价格 数量 优惠卷使用
                // $shop[$num]['list'][$k]['charges'] = bcmul($item->shopGoods->charges,$item->number,2);

                foreach ($v['data'] as $vv) {

                    $v['charges'] += bcmul($vv->shopGoods['charges'], $vv['number'], 2);
                    $v['shop_number'] += $vv['number'];
                    $v['shop_price'] += number_format($vv['price'], 2, '.', '') * $vv['number'];
                     $v['shop_freight'] += $vv->shopGoods['freight'];
                }

                $son['member_id'] = $v['data'][0]['shop_goods']['member_id'];
                $son['area_id'] = ['like','%,'.$address['template_id'].',%'];

                // 运费计算
//                if (Request::instance()->has('combo', 'param')||Request::instance()->has('limited', 'param')){
//                    $v['shop_freight'] = 0;
//                }else{
//                    $freight = (new FreightTemplateModel())->where($son)->value('price');
//
//                    if ($freight) {
//                        $v['shop_freight'] = $freight;
//                    }else{
//                        $v['shop_freight'] = 0;
//                    }
//                }

                // 如果使用优惠卷
                if (!empty($couponids[$num])) {
                    $couponData = $couponModel->where('id', $couponids[$num])->field('id,member_id,shop_id,coupon_id,title,actual_price')->find();
                    //此店铺优惠券id初始化
                    $v['coupon_id'] = $couponData['id'];
                    //优惠券的实际金额
                    $v['coupon_actual_price'] = $couponData['actual_price'];
                    // 使用优惠卷之后的价格
                    $v['shop_price'] -= $v['coupon_actual_price'];
                } else {
                    //此店铺优惠券id初始化
                    $v['coupon_id'] = 0;
                    //此店铺优惠券标题初始化
                    $v['coupon_title'] = "";
                    //优惠券的实际金额
                    $v['coupon_actual_price'] = "";
                }

                //订单总商品数量 订单总价
                $total['total_number'] += $v['shop_number'];
                $total['total_price'] += $v['shop_price'] + $v['shop_freight'];
                $num++;
                $keyArr[] = $k;
            }
        }


        // 使用红包
        if (!empty($packetData)) {
            $opt[$keyArr[0]]['red_packet_id'] = $packetData['id'];
            $opt[$keyArr[0]]['red_actual_price'] = $packetData['actual_price'];
            $opt[$keyArr[0]]['shop_price'] -= $opt[$keyArr[0]]['red_actual_price'];
            $total['total_price'] -= $opt[$keyArr[0]]['red_actual_price'];
        }



        $shop = [];
        $num = 0;
        foreach ($opt as $key => $value) {
            $shop[$num]['title'] = $key;
            foreach ($value['data'] as $k => $item) {
                $shop[$num]['shop_id'] = $item->shopGoods['member_id'];  //店铺id
                $shop[$num]['coupon_id'] = $value['coupon_id'];
                $shop[$num]['coupon_price'] = $value['coupon_actual_price'];
                $shop[$num]['red_packet_id'] = $value['red_packet_id'];
                $shop[$num]['red_packet_price'] = $value['red_actual_price'];
                $shop[$num]['freight'] = $value['shop_freight'];   //单店铺运费合计
                $shop[$num]['price'] = $value['shop_price'];   //单店铺合计
                $shop[$num]['charges'] = $value['charges'];// 佣金
                //商品集合
                $shop[$num]['list'][$k]['goods_id'] = $item->goods_id;
                $shop[$num]['list'][$k]['attr'] = $item->attr;
                $shop[$num]['list'][$k]['number'] = $item->number;
                $shop[$num]['list'][$k]['price'] = $item->price;
                $shop[$num]['list'][$k]['member_id'] = $item->shopGoods->member_id;
                $shop[$num]['list'][$k]['title'] = $item->shopGoods->title;
                $shop[$num]['list'][$k]['thumb_img'] = $item->shopGoods->thumb_img;
                $shop[$num]['list'][$k]['rebate_percentage'] = $item->shopGoods->rebate_percentage;
                $shop[$num]['list'][$k]['limited_status'] = $item->limited_status;
            }
            $num++;
        }
        if (empty(Request::instance()->has('combo', 'param'))) {
            foreach ($opt as &$value) {

                if ($value['data'][0]['limited_status'] == 0) {
                    $str = '';
                    $sid = '';
                    foreach ($value['data'] as $item) {
                        $str .= $item['shopGoods']['goods_id'];
                        $sid = $item['shopGoods']['shop']['member_id'];
                    }
                    $value['coupon'] = self::coupon($sid, $str);
                    $value['red_packet'] = self::red_packet();
                } else {
                    $value['coupon'] = "";
                    $value['red_packet'] = "";
                }

            }
        }


        //转存订单的数据
        $trimData['user_id'] = Session::get('member_id');
        $trimData['address'] = $address;
        $trimData['shop'] = $shop;
        $trimData['cart_id'] = $cart_id;

        // 收获地址列表
        $addressList = (new MemberAddressModel())->where(['member_id' => Session::get('member_id')])->select()->toArray();

        return $this->fetch('', [
            'mate_head'    => '确认订单',
            'act'          => $act,
            'data'         => $opt,
            'total'        => $total,
            'address'      => $address,
            'cart_id'      => $cart_id,
            'combo_has'    => $combo_has,
            'address_list' => $addressList,
            'trimData'     => (new Des())->encrypt(json_encode($trimData)),
        ]);
    }


    public function mop($combo_id, $flag = '')
    {
        // $combo_id = Request::instance()->param('combo_id');

        $data = (new ShopGoodsComboModel())->where('id', $combo_id)->where(['end_time' => ['gt', time()]])
            ->with(['shopGoodsComboSelected' => function ($e) {
                $e
                    ->order('sort desc');
            }])
            ->find();

        if ($data) {
            foreach ($data['shopGoodsComboSelected'] as $value) {
                $value->shopGoods;
                $value->shopSpecAttr;
            }
        }

        $goodsArr = [];
        //运费合计
        $freight = 0;
        foreach ($data->shopGoodsComboSelected as $value) {
            $goodsArr[] = $value->goods_id;
            $freight += $value->shopGoods->freight;
        }
        $info = ShopGoodsModel::where('id', 'in', implode(',', $goodsArr))
            ->field('id,member_id,title,sale_number,picUrl,goods_attr,rebate_percentage,picArr,content,goods_attr,create_time as collection_status,price,rebate_percentage,freight_type,freight,sale_number')
            ->order('id desc')
            ->select();

        foreach ($info as &$value) {
            //            if ($value['goods_attr'] != 'N;'){
            $value['goods_attr'] = unserialize($value['goods_attr']);
            //            }
        }

        if ($flag == 'order_yes') {   //立即购买(确认订单)提供数据
            return $data;
        }
        return $this->fetch('');
    }


    public function combo_list($combo_id, $flag = '')
    {
        // $combo_id = Request::instance()->param('combo_id');

        $data = (new ShopGoodsComboModel())->where('id', $combo_id)->where(['end_time' => ['gt', time()]])
            ->with(['shopGoodsComboSelected' => function ($e) {
                $e
                    ->order('sort desc');
            }])
            ->find();

        if ($data) {
            foreach ($data['shopGoodsComboSelected'] as $value) {
                $value->shopGoods;
                $value->shopSpecAttr;
            }
        }

        $goodsArr = [];
        //运费合计
        $freight = 0;
        foreach ($data->shopGoodsComboSelected as $value) {
            $goodsArr[] = $value->goods_id;
            $freight += $value->shopGoods->freight;
        }
        $info = ShopGoodsModel::where('id', 'in', implode(',', $goodsArr))
            ->field('id,member_id,title,sale_number,picUrl,goods_attr,rebate_percentage,picArr,content,goods_attr,create_time as collection_status,price,rebate_percentage,freight_type,freight,sale_number')
            ->order('id desc')
            ->select();

        foreach ($info as &$value) {
            //            if ($value['goods_attr'] != 'N;'){
            $value['goods_attr'] = unserialize($value['goods_attr']);
            //            }
        }

        if ($flag == 'order_yes') {   //立即购买(确认订单)提供数据
            return $data;
        }

        return $this->fetch('', [
            'data'    => $data,
            'freight' => $freight,
            'info'    => $info,
        ]);
    }


    /**
     * 结算时的优惠券
     */
    public function coupon($shop_id, $cid)
    {
        $memberId = Session::get('member_id');
        $condition = [
            'member_id' => $memberId,
            'shop_id'   => $shop_id,
            'status'    => 2,
            'end_time'  => ['gt', time()],

        ];
        $ini = [
            'sun_member_coupon.member_id' => $memberId,
            'sun_member_coupon.shop_id'   => 0,
            'sun_member_coupon.status'    => 2,
            'sun_coupon.parenTid'         => ['in', $cid],
            'sun_member_coupon.end_time'  => ['gt', time()],
        ];


        $data = Db::name('member_coupon')->where($condition)->select();

        $data0 = Db::view('member_coupon', '*')->view('coupon', 'parenTid,id', 'coupon.id=member_coupon.coupon_id')->where($ini)->select()->toArray();

        if ($data0) {
            array_push($data, $data0);
        }

        return $data;
    }


    /**
     * 结算时的红包
     */
    public function red_packet()
    {
        $memberId = Session::get('member_id');

        $condition = [
            'member_id' => $memberId,
            'status'    => 2,
            // 'end_time'  => ['gt', time()],
        ];

        $data = (new MemberPacketModel())->where($condition)->select()->toArray();

        return $data;
    }


    /*
     * 提交订单&生成订单
     */
    public function commit_order(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();  //trimData 转存的数据 message 客户留言

            $trimData = json_decode((new Des())->decrypt($data['trimData']), true);

            // 判断收货地址是否存在
            if (empty($trimData['address'])) return ['code' => 402, 'message' => '收货地址不能为空'];
            foreach ($trimData['shop'] as $k => &$value) {
                if (mb_strlen($data['message'][$k], "UTF8") > 45) {
                    return ['code' => 402, 'message' => '买家留言过长！'];
                }
                $value['message'] = $data['message'][$k];   //给单店铺赋留言
            }
            //启动事务处理
            Db::startTrans();
            try {
                // 生成总订单号码
                $order_number = createNumber();

                // 处理
                $attachedData = ''; //批量添加附表
                $order_id_Arr = [];  //生成的订单id

                foreach ($trimData['shop'] as $key => &$value) {

                    // 更改优惠券状态
                    if (!empty($value['coupon_id'])) {

                        // 优惠券改变状态
                        Db::name('member_coupon')->where('id', $value['coupon_id'])->update(['status' => '1']);

                    }

                    // 更改红包状态
                    if (!empty($value['red_packet_id'])) {

                        // 红包改变状态
                        Db::name('member_packet')->where(['member_id' => Session::get('member_id'), 'status' => '2', 'start_time' => ['lt', time()], 'end_time' => ['gt', time()], 'packet_id' => $value['red_packet_id']])->update(['status' => '1']);

                    }

                    // 店铺订单号
                    $shop_order_number = make_order(Session::get('member_id'));
                    // if(Cache::get('web_rebate_percentage') == "Y") {
                    // 分销生成订单记录
                    $this->brokerage(Session::get('member_id'), $value['charges'], $shop_order_number, $value['shop_id']);
                    // }


                    // 主表信息
                    $information = [
                        'shop_id'           => $value['shop_id'],
                        'member_id'         => Session::get('member_id'),
                        'order_number'      => $order_number,
                        'shop_order_number' => $shop_order_number,
                        'coupon_id'         => $value['coupon_id'],
                        'coupon_price'      => $value['coupon_price'],
                        'red_packet_id'     => $value['red_packet_id'],
                        'red_packet_price'  => $value['red_packet_price'],
                        'freight'           => $value['freight'],
                        'price'             => $value['price'],
                        'message'           => $value['message'],
                        // 'goods'             => serialize($value['list']),
                        'address_name'      => $trimData['address']['name'],
                        'address_phone'     => $trimData['address']['phone'],
                        'address_area'      => $trimData['address']['area_info'],
                        'address_site'      => $trimData['address']['address'],
                        'status'            => '0',
                        'way'               => '未支付',
                        // 'single_way'        => 3,
                        'create_time'       => time()
                    ];

                    // 插入订单主表
                    $order_id = Db::name('member_order')->insertGetId($information);
                    $order_id_Arr[] = $shop_order_number;

                    foreach ($value['list'] as $val) {
                        if (!empty($val['attr'])) {

                            // 减少属性表库存
                            $inventory_attr = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('inventory');
                            if ($inventory_attr < $val['number']) {
                                return ['code' => 401, 'message' => $val['title'] . '(' . $val['attr'] . '),库存不足'];
                            }

                            Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->setDec('inventory', $val['number']);
                        }

                        // 减少主表库存
                        $inventory_find = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('inventory');
                        if ($inventory_find < $val['number']) {
                            return ['code' => 401, 'message' => $val['title'] . ',库存不足'];
                        }

                        Db::name('shop_goods')->where(['id' => $val['goods_id']])->setDec('inventory', $val['number']);
                        Db::name('shop_goods')->where(['id' => $val['goods_id']])->setInc('sale_number', $val['number']);

                        $attachedData[] = [
                            'order_id'          => $order_id,
                            'order_number'      => $order_number,
                            'shop_order_number' => $shop_order_number,
                            'goods_id'          => $val['goods_id'],
                            'attr'              => $val['attr'],
                            'number'            => $val['number'],
                            'price'             => $val['price'],
                            'title'             => $val['title'],
                            'thumb_img'         => $val['thumb_img'],
                            'rebate_percentage' => $val['rebate_percentage'],
                            'limited_status'    => $val['limited_status'],
                            'status'            => '2'
                        ];
                        //是否为特价商品
                        if (!empty($val['limited_status'])) {
                            //查找特价商品的限制数量和已购买数量
                            $limited = Db::name('limited')->where(['goods_id' => $val['goods_id']])->field('number,purchase_number')->find();

                            if (!empty($limited)) {

                                if (($limited['purchase_number'] + $val['number']) > $limited['number']) return ['code' => 402, 'message' => '特价商品数量不够,请调整购物车再进行购买'];
                                // 是否是特价
                                Db::name('limited')->where(['goods_id' => $val['goods_id']])->setInc('purchase_number', $val['number']);

                            }


                        }

                    }

                }

                // 批量插入附表
                Db::name('member_order_attached')->insertAll($attachedData);

                // 删除此次购物车的记录
                MemberShoppingCartModel::destroy($trimData['cart_id']);

                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);

                // 提交事务
                Db::commit();

                return ['code' => 200, 'oid' => implode(',', $order_id_Arr)];

            } catch (\Exception $e) {

                //回滚事务
                Db::rollback();
                return ['code' => 0, 'message' => $e->getMessage()];
            }
        }
    }


    /*
     * 查询商品是否为限购商品
     */
    public function query_limited(Request $request)
    {
        if ($request->isPost()) {
            $id = $request->post('id');
            $limited = (new MemberShoppingCartModel())->where('id', $id)->value('limited_status');
            return $limited;
        }
    }


    /*
    * 查询商品库存
    */
    public function query_inventory(Request $request)
    {
        if ($request->isPost()) {
            $goods_id = $request->post('id');
            $cart_id = $request->post('cart_id');
            $num = $request->post('num');
            $inventory = (new ShopGoodsModel())->where('id', $goods_id)->value('inventory');

            if ($num >= $inventory) {
                return ['code' => 400, 'message' => '商品库存数量不足'];
            } else {
                (new MemberShoppingCartModel())->where('id', $cart_id)->setInc('number');
                return ['code' => 200];
            }
        }
    }


    /**
     * 购物车商品数减少
     */
    public function query_reduce()
    {
        if (Request::instance()->isPost()) {
            // 获取参数
            $data = Request::instance()->param('cart_id');

            $operation = (new MemberShoppingCartModel())->where(['id' => $data])->setDec('number');

            if ($operation) {

                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);

                return ['code' => 200];
            } else {
                return ['code' => 402];
            }
        }
    }


    /**
     * 购物车添加
     */
    public function default_cart(Request $request)
    {
        if (Request::instance()->isPost()) {

            // 获取会员ID
            $member_id = Session::get('member_id');

            // 判断是否登录
            if (!$member_id) {
                return ['code' => 401, 'message' => '您还未登录,请登录'];
            }

            // 获取参数
            $map['goods_id'] = Request::instance()->param('id');
            $map['attr'] = Request::instance()->param('attr');
            $map['number'] = Request::instance()->param('num');
            $map['price'] = Request::instance()->param('price');
            $map['member_id'] = $member_id;   //会员id

            // 是否是本店铺
            $member = (new ShopGoodsModel)->where(['id' => $map['goods_id']])->field('member_id,price')->find();
            if ($member['member_id'] == $member_id) {
                return ['code' => 402, 'message' => '不能添加自己的商品'];
            }

            // 查找购物车是否有相同收藏
            $model = new MemberShoppingCartModel();
            $status = $model->where(['member_id' => $member_id, 'goods_id' => $map['goods_id'], 'attr' => $map['attr']])->find();

            // 判断商品库存
            $stock = (int)(new ShopGoodsModel())->where('id', $map['goods_id'])->value('inventory');

            if ($stock < $map['number']) return ['code' => 402, 'message' => '库存不足！不能添加购物车！'];

            // 查看分库存
            $sub_inventory = (new ShopSpecAttr())->where(['goods_id' => $map['goods_id'], 'attribute' => $map['attr']])->find();

            if ($sub_inventory) {
                if ((int)$sub_inventory['inventory'] < $map['number']) return ['code' => 402, 'message' => '该属性库存不足！请改日再购买！'];
            }

            if ($status) {
                //有则合并
                $res = $model->isUpdate(true)->where('id', $status['id'])->setInc('number', $map['number']);
                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);

                return $res ? ['code' => 200, 'message' => '添加成功'] : ['code' => 0, 'message' => '网络繁忙'];
            } else {
                //没有则新增
                $res = $model->isUpdate(false)->allowField(true)->save($map);
                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);
                return $res ? ['code' => 200, 'message' => '添加成功'] : ['code' => 0, 'message' => '网络繁忙'];
            }

        }
    }


    /**
     * 删除购物车内的商品
     */
    public function cart_del(Request $request)
    {
        if ($request->isPost()) {
            $id = $request->post('id');  //要删除的id或id串
            if ($id) {
                $result = MemberShoppingCartModel::destroy($id);

                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);

                return $result ? ['code' => 200, 'message' => '删除成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
            }
            return ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }


    /**
     * 批量删除商品
     */
    public function delete_all()
    {
        if (Request::instance()->isPost()) {
            // 获取要删除的IDS
            $ids = Request::instance()->param('ids');
            // 执行删除
            $operation = (new MemberShoppingCartModel())->where('id', 'in', $ids)->delete();

            if ($operation) {

                // 更新购物车数量
                $cart = (new MemberShoppingCartModel())->where('member_id', Session::get('member_id'))->count();
                Session::set('shop_cart', $cart);

                return ['code' => 200];
            } else {
                return ['code' => 402];
            }
        }


    }


    // 增加购物车商品数量
    public function charge_number()
    {
        $id = Request::instance()->param('id');
        $number = Request::instance()->param('number');

        $operation = (new MemberShoppingCartModel())->allowField(true)->save(['number'=>$number],['id'=>$id]);

        if ($operation) {
            return ['code'=>200];
        }else{
            return ['code'=>400];
        }

    }


}